<template>
  <div class="breadcrumb">
    <el-button
      icon="ArrowLeftBold"
      round
      type="info"
      plain
      title="返回"
      v-if="showBack"
      @click="handleBack"
    />
    <el-breadcrumb
      class="app-breadcrumb"
      separator="/"
    >
      <transition-group name="breadcrumb">
        <el-breadcrumb-item
          v-for="(item,index) in levelList"
          :key="item.path"
        >
          <span
            v-if="item.redirect==='noRedirect'||index==levelList.length-1"
            class="no-redirect"
          >{{ item.meta.title }}</span>
          <a
            v-else
            @click.prevent="handleLink(item)"
          >{{ item.meta.title }}</a>
        </el-breadcrumb-item>
      </transition-group>
    </el-breadcrumb>
  </div>
</template>

<script lang="ts" setup >
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter, useRoute, RouteLocationMatched } from 'vue-router'

const route = useRoute()
const router = useRouter()
const levelList = ref<RouteLocationMatched[]>([])

const showBack = computed(() => {
  return route.meta.back
})
const handleBack = () => {
  router.go(-1)
}

watch(() => route, () => {
  getBreadcrumb()
}, {
  deep: true
})

onMounted(() => {
  getBreadcrumb()
})

const getBreadcrumb = () => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)

  levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
}

const handleLink = (item:RouteLocationMatched) => {
  const { path, redirect } = item
  if (redirect) {
    router.push(path)
  }
  router.push(path)
}
</script>

<style lang="scss" scoped>
.breadcrumb{
  display: flex;
  align-items: center;
  padding: 0 10px;
}
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
